<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考勤记录模板</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #fff;
            padding-right: 200px;
            position: relative;
        }
        .container {
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            position: relative;
            z-index: 1;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        }
        .control-panel {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            width: 160px;
            display: flex;
            flex-direction: column;
            gap: 15px;
            padding: 15px;
            background-color: #f0f8ff;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
            z-index: 100;
            backdrop-filter: blur(5px);
        }
        .control-group {
            display: flex;
            flex-direction: column;
        }
        label {
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
            font-size: 14px;
        }
        select, input, button, textarea {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.2s;
        }
        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        button {
            color: white;
            border: none;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
            height: 36px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 6px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        button:hover {
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0,0,0,0.15);
        }
        #result {
            margin-top: 20px;
            overflow-x: auto;
            position: relative;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            margin-bottom: 30px;
            font-size: 12px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
            position: sticky;
            top: 0;
            font-weight: 600;
            color: #333;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .normal {
            color: green;
        }
        .absent {
            color: red;
        }
        .weekend {
            background-color: #f0f0f0;
        }
        .holiday {
            background-color: #fff0f0;
        }
        .workday {
            background-color: #e6f7ff;
        }
        .overtime {
            background-color: #fff8e6;
        }
        .excel-btn {
            background: linear-gradient(135deg, #4CAF50 0%, #2E7D32 100%);
        }
        .title {
            text-align: center;
            margin-bottom: 15px;
        }
        @media (max-width: 768px) {
            body {
                padding-right: 20px;
                padding-bottom: 200px;
            }
            .control-panel {
                top: auto;
                bottom: 20px;
                left: 50%;
                transform: translateX(-50%);
                width: calc(100% - 80px);
                max-width: 400px;
                flex-direction: row;
                flex-wrap: wrap;
                justify-content: center;
            }
            .control-group {
                width: 120px;
            }
        }
        .stats {
            margin-top: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 6px;
            font-size: 14px;
        }
        .stats p {
            margin: 5px 0;
        }
        .stats span {
            font-weight: 600;
            color: #667eea;
        }
        .view-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        .view-tab {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            background-color: #f0f0f0;
            transition: all 0.2s;
        }
        .view-tab.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
    </style>
    <!-- 引入SheetJS库用于导出Excel -->
    <script src="../js/xlsx.full.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="view-tabs">
            <div class="view-tab active" data-view="summary">月度统计</div>
            <div class="view-tab" data-view="detail">原始记录</div>
        </div>
        <div id="result"></div>
    </div>

    <div class="control-panel">
        <div class="control-group">
            <label for="employeeName">姓名(每行一个姓名):</label>
            <textarea id="employeeName" rows="5" placeholder="每行输入一个姓名"></textarea>
        </div>
        
        <div class="control-group">
            <label for="attendanceAddress">打卡地址:</label>
            <input type="text" id="attendanceAddress" placeholder="输入打卡地址" value="麒龙CBD中心B座">
        </div>
        
        <div class="control-group">
            <label for="year">年份:</label>
            <select id="year"></select>
        </div>
        
        <div class="control-group">
            <label for="month">月份:</label>
            <select id="month">
                <option value="1">1月</option>
                <option value="2">2月</option>
                <option value="3">3月</option>
                <option value="4">4月</option>
                <option value="5">5月</option>
                <option value="6">6月</option>
                <option value="7">7月</option>
                <option value="8">8月</option>
                <option value="9">9月</option>
                <option value="10">10月</option>
                <option value="11">11月</option>
                <option value="12">12月</option>
            </select>
        </div>
        
        <div class="control-group">
            <label for="holidaySettings">节假日设置:</label>
            <textarea id="holidaySettings" placeholder="格式:月-日=节假日名称，如:1-1=元旦"></textarea>
        </div>
        
        <div class="control-group">
            <label for="workdaySettings">补班日期:</label>
            <textarea id="workdaySettings" placeholder="格式:月-日，如:1-28"></textarea>
        </div>
        
        <div class="control-group">
            <label for="leaveSettings">请假日期设置:</label>
            <textarea id="leaveSettings" placeholder="格式:姓名,月-日=请假类型，如:张三,5-2=病假"></textarea>
        </div>
        
        <div class="control-group">
            <label for="overtimeSettings">加班日期设置:</label>
            <textarea id="overtimeSettings" placeholder="格式:姓名,月-日=加班类型，如:张三,5-2=工作日加班"></textarea>
        </div>
        
        <button id="generateBtn">查询</button>
        <button id="exportExcelBtn" class="excel-btn">导出Excel</button>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 设置当前月份和年份
            const currentDate = new Date();
            const currentYear = currentDate.getFullYear();
            const currentMonth = currentDate.getMonth() + 1;
            
            // 生成年份选择器（当前年份及前五年）
            const yearSelect = document.getElementById('year');
            for (let year = currentYear; year >= currentYear - 5; year--) {
                const option = document.createElement('option');
                option.value = year;
                option.textContent = year;
                if (year === currentYear) {
                    option.selected = true;
                }
                yearSelect.appendChild(option);
            }
            
            document.getElementById('month').value = currentMonth;
            
            // 视图模式
            let currentView = 'summary';
            // 存储生成的考勤数据，以便在两个视图间共享
            let attendanceData = {};
            
            // 视图切换
            document.querySelectorAll('.view-tab').forEach(tab => {
                tab.addEventListener('click', () => {
                    document.querySelectorAll('.view-tab').forEach(t => t.classList.remove('active'));
                    tab.classList.add('active');
                    currentView = tab.dataset.view;
                    
                    // 如果已经生成了记录，则立即切换视图
                    if (Object.keys(attendanceData).length > 0) {
                        renderAttendanceView();
                    }
                });
            });
            
            // 生成按钮点击事件
            document.getElementById('generateBtn').addEventListener('click', generateAttendance);
            
            // 导出Excel按钮点击事件
            document.getElementById('exportExcelBtn').addEventListener('click', exportToExcel);
            
            // 生成考勤记录函数
            function generateAttendance() {
                const employeeNames = document.getElementById('employeeName').value.split('\n').map(name => name.trim()).filter(name => name);
                if (employeeNames.length === 0) {
                    alert('请输入至少一个员工姓名');
                    return;
                }
                
                const year = parseInt(document.getElementById('year').value);
                const month = parseInt(document.getElementById('month').value);
                const attendanceAddress = document.getElementById('attendanceAddress').value || '麒龙CBD中心B座';
                const absentProbability = 2; // 固定补卡概率2%
                
                // 解析节假日设置
                const holidays = {};
                const holidayText = document.getElementById('holidaySettings').value;
                holidayText.split('\n').forEach(line => {
                    const parts = line.trim().split('=');
                    if (parts.length === 2 && parts[0].trim() && parts[1].trim()) {
                        holidays[parts[0].trim()] = parts[1].trim();
                    }
                });
                
                // 解析补班日期设置
                const workdays = [];
                const workdayText = document.getElementById('workdaySettings').value;
                workdayText.split('\n').forEach(line => {
                    const dateStr = line.trim();
                    if (dateStr) {
                        workdays.push(dateStr);
                    }
                });
                
                // 解析请假日期设置
                const leaveSettings = {};
                employeeNames.forEach(name => leaveSettings[name] = []);
                const leaveText = document.getElementById('leaveSettings').value;
                leaveText.split('\n').forEach(line => {
                    const parts = line.trim().split('=');
                    if (parts.length === 2 && parts[0].trim() && parts[1].trim()) {
                        const nameDate = parts[0].split(',');
                        if (nameDate.length === 2 && nameDate[0].trim() && nameDate[1].trim()) {
                            const name = nameDate[0].trim();
                            const date = nameDate[1].trim();
                            if (employeeNames.includes(name)) {
                                leaveSettings[name].push({date, type: parts[1].trim()});
                            }
                        }
                    }
                });
                
                // 解析加班日期设置
                const overtimeSettings = {};
                employeeNames.forEach(name => overtimeSettings[name] = []);
                const overtimeText = document.getElementById('overtimeSettings').value;
                overtimeText.split('\n').forEach(line => {
                    const parts = line.trim().split('=');
                    if (parts.length === 2 && parts[0].trim() && parts[1].trim()) {
                        const nameDate = parts[0].split(',');
                        if (nameDate.length === 2 && nameDate[0].trim() && nameDate[1].trim()) {
                            const name = nameDate[0].trim();
                            const date = nameDate[1].trim();
                            if (employeeNames.includes(name)) {
                                overtimeSettings[name].push({date, type: parts[1].trim()});
                            }
                        }
                    }
                });
                
                // 为员工分配固定的设备ID
                const employeeDevices = {};
                employeeNames.forEach(name => {
                    const deviceId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
                    employeeDevices[name] = `手机_${deviceId}`;
                });
                
                // 生成考勤数据
                attendanceData = generateAttendanceData(year, month, employeeNames, employeeDevices, attendanceAddress, holidays, workdays, leaveSettings, overtimeSettings, absentProbability);
                
                // 渲染视图
                renderAttendanceView();
            }
            
            // 生成考勤数据
            function generateAttendanceData(year, month, employeeNames, employeeDevices, attendanceAddress, holidays, workdays, leaveSettings, overtimeSettings, absentProbability) {
                const data = {};
                const daysInMonth = new Date(year, month, 0).getDate();
                
                employeeNames.forEach((employeeName, index) => {
                    // 随机生成员工信息
                    const departments = ["技术实施-技术二部"];
                    const positions = ["售前工程师"];
                    
                    // 工号按照顺序编号，如JS-0001，JS-0002
                    const id = `JS-${(index + 1).toString().padStart(4, '0')}`;
                    
                    const info = {
                        group: "09:00-17:00考勤组",
                        department: departments[Math.floor(Math.random() * departments.length)],
                        id: id,
                        position: positions[Math.floor(Math.random() * positions.length)],
                        device: employeeDevices[employeeName]
                    };
                    
                    data[employeeName] = {
                        info: info,
                        records: []
                    };
                    
                    // 记录补卡次数
                    let absentCount = 0;
                    // 记录补卡日期
                    const absentDates = [];
                    
                    // 只循环当月实际天数
                    for (let day = 1; day <= daysInMonth; day++) {
                        const date = new Date(year, month - 1, day);
                        const dayOfWeek = date.getDay(); // 0=周日, 1=周一, ..., 6=周六
                        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
                        
                        // 检查是否是节假日
                        const holidayKey = `${month}-${day}`;
                        const isHoliday = holidays[holidayKey];
                        
                        // 检查是否是补班日
                        const isWorkday = workdays.includes(holidayKey);
                        
                        // 检查是否是请假
                        const isLeave = (leaveSettings[employeeName] || []).some(leave => leave.date === holidayKey);
                        const leaveType = (leaveSettings[employeeName] || []).find(leave => leave.date === holidayKey)?.type || '请假';
                        
                        // 检查是否是加班
                        const isOvertime = (overtimeSettings[employeeName] || []).some(ot => ot.date === holidayKey);
                        const overtimeType = (overtimeSettings[employeeName] || []).find(ot => ot.date === holidayKey)?.type || '加班';
                        
                        // 考勤日期格式化 - 使用完整的4位年份
                        const dateStr = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
                        const dayOfWeekStr = ['日', '一', '二', '三', '四', '五', '六'][dayOfWeek];
                        const fullDateStr = `${dateStr} 星期${dayOfWeekStr}`;
                        const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
                        
                        // 初始化记录对象
                        const record = {
                            date: fullDateStr,
                            formattedDate: formattedDate,
                            dayOfWeek: dayOfWeek,
                            isWeekend: isWeekend,
                            isHoliday: isHoliday,
                            isWorkday: isWorkday,
                            isLeave: isLeave,
                            leaveType: leaveType,
                            isOvertime: isOvertime,
                            overtimeType: overtimeType,
                            attendanceTime: '',
                            checkInTime: '',
                            checkOutTime: '',
                            checkInResult: '',
                            checkOutResult: '',
                            cellClassIn: '',
                            cellClassOut: '',
                            address: attendanceAddress,
                            remark: '',
                            reasonIn: '',
                            reasonOut: '',
                            deviceIn: employeeDevices[employeeName],
                            deviceOut: employeeDevices[employeeName],
                            adminRemark: ''
                        };
                        
                        if (isLeave) {
                            record.attendanceTime = '-';
                            record.checkInTime = '-';
                            record.checkOutTime = '-';
                            record.checkInResult = leaveType;
                            record.checkOutResult = leaveType;
                            record.cellClassIn = 'holiday';
                            record.cellClassOut = 'holiday';
                            record.remark = `${leaveType}请假`;
                            record.address = '';
                            record.deviceIn = '';
                            record.deviceOut = '';
                        } else if (isOvertime) {
                            // 加班日
                            record.attendanceTime = `${formattedDate} 09:00；${formattedDate} 17:00；${formattedDate} 20:00`;
                            record.cellClassIn = 'overtime';
                            record.cellClassOut = 'overtime';
                            
                            // 上班时间
                            const inMinute = 50 + Math.floor(Math.random() * 10); // 8:50-9:00之间
                            record.checkInTime = `${formattedDate} 08:${inMinute.toString().padStart(2, '0')}`;
                            record.checkInResult = '正常';
                            record.cellClassIn = 'normal';
                            
                            // 下班时间
                            const outMinute = Math.floor(Math.random() * 60);
                            record.checkOutTime = `${formattedDate} 20:${outMinute.toString().padStart(2, '0')}`;
                            record.checkOutResult = '加班';
                            record.cellClassOut = 'overtime';
                            record.remark = overtimeType;
                        } else if (isWorkday) {
                            // 补班日需要打卡
                            record.attendanceTime = `${formattedDate} 09:00；${formattedDate} 17:00`;
                            record.cellClassIn = 'workday';
                            record.cellClassOut = 'workday';
                            
                            // 上班时间
                            const inMinute = 50 + Math.floor(Math.random() * 10); // 8:50-9:00之间
                            record.checkInTime = `${formattedDate} 08:${inMinute.toString().padStart(2, '0')}`;
                            record.checkInResult = '正常';
                            record.cellClassIn = 'normal';
                            
                            // 下班时间
                            const outMinute = Math.floor(Math.random() * 60);
                            record.checkOutTime = `${formattedDate} 17:${outMinute.toString().padStart(2, '0')}`;
                            record.checkOutResult = '正常';
                            record.cellClassOut = 'normal';
                        } else if (isWeekend) {
                            record.attendanceTime = '-';
                            record.checkInTime = '-';
                            record.checkOutTime = '-';
                            record.checkInResult = '休息';
                            record.checkOutResult = '休息';
                            record.cellClassIn = 'weekend';
                            record.cellClassOut = 'weekend';
                            record.address = '';
                            record.deviceIn = '';
                            record.deviceOut = '';
                        } else if (isHoliday) {
                            record.attendanceTime = '-';
                            record.checkInTime = '-';
                            record.checkOutTime = '-';
                            record.checkInResult = isHoliday;
                            record.checkOutResult = isHoliday;
                            record.cellClassIn = 'holiday';
                            record.cellClassOut = 'holiday';
                            record.address = '';
                            record.deviceIn = '';
                            record.deviceOut = '';
                        } else {
                            // 工作日考勤数据
                            record.attendanceTime = `${formattedDate} 09:00；${formattedDate} 17:00`;
                            
                            // 检查是否已经达到补卡上限
                            const canAbsent = absentCount < 3;
                            
                            // 随机决定是否补卡
                            let isAbsentIn = false;
                            let isAbsentOut = false;
                            
                            if (canAbsent) {
                                isAbsentIn = Math.random() * 100 < absentProbability;
                                isAbsentOut = Math.random() * 100 < absentProbability;
                                
                                // 确保每人不超过3次补卡
                                if (isAbsentIn || isAbsentOut) {
                                    absentCount++;
                                    absentDates.push(formattedDate);
                                }
                            }
                            
                            if (isAbsentIn) {
                                record.checkInTime = '-';
                                record.checkInResult = '补卡';
                                record.cellClassIn = 'absent';
                                record.reasonIn = '忘记打卡';
                                record.adminRemark = '补卡审批通过';
                            } else {
                                // 上班时间
                                const inMinute = 50 + Math.floor(Math.random() * 10); // 8:50-9:00之间
                                record.checkInTime = `${formattedDate} 08:${inMinute.toString().padStart(2, '0')}`;
                                record.checkInResult = '正常';
                                record.cellClassIn = 'normal';
                            }
                            
                            if (isAbsentOut) {
                                record.checkOutTime = '-';
                                record.checkOutResult = '补卡';
                                record.cellClassOut = 'absent';
                                record.reasonOut = '忘记打卡';
                                record.adminRemark = '补卡审批通过';
                            } else {
                                // 下班时间
                                const outMinute = Math.floor(Math.random() * 60);
                                record.checkOutTime = `${formattedDate} 17:${outMinute.toString().padStart(2, '0')}`;
                                record.checkOutResult = '正常';
                                record.cellClassOut = 'normal';
                            }
                        }
                        
                        data[employeeName].records.push(record);
                    }
                });
                
                return data;
            }
            
            // 渲染考勤视图
            function renderAttendanceView() {
                if (currentView === 'detail') {
                    renderDetailView();
                } else {
                    renderSummaryView();
                }
            }
            
            // 渲染原始记录视图
            function renderDetailView() {
                const year = parseInt(document.getElementById('year').value);
                const month = parseInt(document.getElementById('month').value);
                
                // 创建表头
                let headerRow = '<tr><th>姓名</th><th>考勤组</th><th>部门</th><th>工号</th><th>职位</th><th>考勤日期</th><th>考勤时间</th><th>打卡时间</th><th>打卡结果</th><th>打卡地址</th><th>打卡备注</th><th>异常打卡原因</th><th>打卡图片1</th><th>打卡图片2</th><th>打卡设备</th><th>管理员修改备注</th><th>管理员修改备注图片1</th><th>管理员修改备注图片2</th><th>管理员修改备注图片3</th></tr>';
                
                let resultHTML = `
                    <div class="title"><h2>${year}年${month}月考勤记录导出 - 原始记录</h2></div>
                    <table>
                        <thead>
                            ${headerRow}
                        </thead>
                        <tbody>
                `;
                
                // 为每个员工生成考勤记录
                for (const employeeName in attendanceData) {
                    const employeeData = attendanceData[employeeName];
                    const info = employeeData.info;
                    
                    employeeData.records.forEach(record => {
                        // 生成上班打卡记录
                        let rowHTMLIn = `<tr><td>${employeeName}</td><td>${info.group}</td><td>${info.department}</td><td>${info.id}</td><td>${info.position}</td>`;
                        rowHTMLIn += `<td>${record.date}</td>`;
                        rowHTMLIn += `<td>${record.attendanceTime.split('；')[0] || '-'}</td><td>${record.checkInTime}</td><td class="${record.cellClassIn}">${record.checkInResult}</td><td>${record.address}</td><td>${record.remark}</td><td>${record.reasonIn}</td>`;
                        rowHTMLIn += `<td></td><td></td>`;
                        rowHTMLIn += `<td>${record.deviceIn}</td><td>${record.adminRemark}</td><td></td><td></td><td></td>`;
                        rowHTMLIn += '</tr>';
                        resultHTML += rowHTMLIn;
                        
                        // 生成下班打卡记录
                        let rowHTMLOut = `<tr><td>${employeeName}</td><td>${info.group}</td><td>${info.department}</td><td>${info.id}</td><td>${info.position}</td>`;
                        rowHTMLOut += `<td>${record.date}</td>`;
                        rowHTMLOut += `<td>${record.attendanceTime.split('；')[1] || '-'}</td><td>${record.checkOutTime}</td><td class="${record.cellClassOut}">${record.checkOutResult}</td><td>${record.address}</td><td>${record.remark}</td><td>${record.reasonOut}</td>`;
                        rowHTMLOut += `<td></td><td></td>`;
                        rowHTMLOut += `<td>${record.deviceOut}</td><td>${record.adminRemark}</td><td></td><td></td><td></td>`;
                        rowHTMLOut += '</tr>';
                        resultHTML += rowHTMLOut;
                        
                        // 如果是加班日，生成加班打卡记录
                        if (record.isOvertime) {
                            let rowHTMLOvertime = `<tr><td>${employeeName}</td><td>${info.group}</td><td>${info.department}</td><td>${info.id}</td><td>${info.position}</td>`;
                            rowHTMLOvertime += `<td>${record.date}</td>`;
                            rowHTMLOvertime += `<td>${record.attendanceTime.split('；')[2] || '-'}</td><td>${record.checkOutTime}</td><td class="${record.cellClassOut}">加班</td><td>${record.address}</td><td>${record.remark}</td><td></td>`;
                            rowHTMLOvertime += `<td></td><td></td>`;
                            rowHTMLOvertime += `<td>${record.deviceOut}</td><td></td><td></td><td></td><td></td>`;
                            rowHTMLOvertime += '</tr>';
                            resultHTML += rowHTMLOvertime;
                        }
                    });
                }
                
                resultHTML += `
                    </tbody>
                </table>
                `;
                
                document.getElementById('result').innerHTML = resultHTML;
            }
            
            // 渲染月度统计视图
            function renderSummaryView() {
                const year = parseInt(document.getElementById('year').value);
                const month = parseInt(document.getElementById('month').value);
                const daysInMonth = new Date(year, month, 0).getDate();
                
                // 创建表头 - 只生成当月实际天数的列
                let headerRow = '<tr><th>月份</th><th>姓名</th><th>出勤天数</th><th>休息天数</th><th>加班天数</th><th>请假天数</th>';
                for (let day = 1; day <= daysInMonth; day++) {
                    headerRow += `<th>${day}日</th>`;
                }
                headerRow += '</tr>';
                
                let resultHTML = `
                    <div class="title"><h2>${year}年${month}月考勤记录导出 - 月度统计</h2></div>
                    <table>
                        <thead>
                            ${headerRow}
                        </thead>
                        <tbody>
                `;
                
                // 为每个员工生成考勤记录
                for (const employeeName in attendanceData) {
                    const employeeData = attendanceData[employeeName];
                    
                    let rowHTML = `<tr><td>${month}月</td><td>${employeeName}</td>`;
                    
                    // 统计信息
                    let attendanceDays = 0;
                    let restDays = 0;
                    let overtimeDays = 0;
                    let leaveDays = 0;
                    
                    employeeData.records.forEach(record => {
                        let cellContent = '';
                        let cellValue = '';
                        let cellClass = '';
                        
                        if (record.isLeave) {
                            cellContent = `${record.leaveType}<br>(-)`;
                            cellValue = record.leaveType;
                            cellClass = 'holiday';
                            leaveDays++;
                            restDays++;
                        } else if (record.isOvertime) {
                            // 加班日
                            cellClass = 'overtime';
                            attendanceDays++;
                            overtimeDays++;
                            
                            // 从打卡时间中提取时间部分
                            const checkInTime = record.checkInTime.split(' ')[1];
                            const checkOutTime = record.checkOutTime.split(' ')[1];
                            cellContent = `加班<br>(${checkInTime},${checkOutTime})`;
                            cellValue = `加班(${checkInTime},${checkOutTime})`;
                        } else if (record.isWorkday) {
                            // 补班日需要打卡
                            cellClass = 'workday';
                            attendanceDays++;
                            
                            // 从打卡时间中提取时间部分
                            const checkInTime = record.checkInTime.split(' ')[1];
                            const checkOutTime = record.checkOutTime.split(' ')[1];
                            cellContent = `补班<br>(${checkInTime},${checkOutTime})`;
                            cellValue = `补班(${checkInTime},${checkOutTime})`;
                        } else if (record.isWeekend) {
                            cellContent = `休息<br>(-)`;
                            cellValue = "休息";
                            cellClass = 'weekend';
                            restDays++;
                        } else if (record.isHoliday) {
                            cellContent = `${record.isHoliday}<br>(-)`;
                            cellValue = record.isHoliday;
                            cellClass = 'holiday';
                            restDays++;
                        } else {
                            // 工作日考勤数据
                            if (record.checkInResult === '补卡' || record.checkOutResult === '补卡') {
                                cellContent = `补卡<br>(-)`;
                                cellValue = "补卡";
                                cellClass = 'absent';
                                attendanceDays++;
                            } else {
                                // 从打卡时间中提取时间部分
                                const checkInTime = record.checkInTime.split(' ')[1];
                                const checkOutTime = record.checkOutTime.split(' ')[1];
                                cellContent = `正常<br>(${checkInTime},${checkOutTime})`;
                                cellValue = `正常(${checkInTime},${checkOutTime})`;
                                cellClass = 'normal';
                                attendanceDays++;
                            }
                        }
                        
                        rowHTML += `<td class="${cellClass}" data-value="${cellValue}">${cellContent}</td>`;
                    });
                    
                    // 添加统计信息
                    rowHTML = rowHTML.replace(`<td>${employeeName}</td>`, 
                        `<td>${employeeName}</td><td>${attendanceDays}</td><td>${restDays}</td><td>${overtimeDays}</td><td>${leaveDays}`);
                    
                    rowHTML += '</tr>';
                    resultHTML += rowHTML;
                }
                
                resultHTML += `
                        </tbody>
                    </table>
                `;
                
                document.getElementById('result').innerHTML = resultHTML;
            }
            
            // 导出Excel函数
            function exportToExcel() {
                // 获取表格元素
                const table = document.querySelector('table');
                if (!table) {
                    alert('请先生成考勤表');
                    return;
                }
                
                // 创建工作簿
                const wb = XLSX.utils.book_new();
                
                // 将表格转换为工作表
                const ws = XLSX.utils.table_to_sheet(table);
                
                // 调整列宽
                const wscols = currentView === 'detail' ? [
                    {wch: 10}, // 姓名列宽
                    {wch: 15}, // 考勤组列宽
                    {wch: 25}, // 部门列宽（增加宽度以适应更长的部门名称）
                    {wch: 12}, // 工号列宽
                    {wch: 15}, // 职位列宽
                    {wch: 18}, // 考勤日期列宽
                    {wch: 25}, // 考勤时间列宽
                    {wch: 25}, // 打卡时间列宽
                    {wch: 12}, // 打卡结果列宽
                    {wch: 15}, // 打卡地址列宽
                    {wch: 15}, // 打卡备注列宽
                    {wch: 15}, // 异常打卡原因列宽
                    {wch: 15}, // 打卡图片1列宽
                    {wch: 15}, // 打卡图片2列宽
                    {wch: 30}, // 打卡设备列宽
                    {wch: 15}, // 管理员修改备注列宽
                    {wch: 15}, // 管理员修改备注图片1列宽
                    {wch: 15}, // 管理员修改备注图片2列宽
                    {wch: 15}  // 管理员修改备注图片3列宽
                ] : [
                    {wch: 8}, // 月份列宽
                    {wch: 10}, // 姓名列宽
                    {wch: 10}, // 出勤天数列宽
                    {wch: 10}, // 休息天数列宽
                    {wch: 10}, // 加班天数列宽
                    {wch: 10}  // 请假天数列宽
                ];
                
                // 如果是汇总视图，添加日期列的宽度
                if (currentView === 'summary') {
                    const daysInMonth = new Date(parseInt(document.getElementById('year').value), parseInt(document.getElementById('month').value), 0).getDate();
                    for (let i = 0; i < daysInMonth; i++) {
                        wscols.push({wch: 15});
                    }
                }
                
                ws['!cols'] = wscols;
                
                // 添加工作表到工作簿
                XLSX.utils.book_append_sheet(wb, ws, currentView === 'detail' ? "原始记录" : "月度统计");
                
                // 生成Excel文件并下载
                const year = document.getElementById('year').value;
                const month = document.getElementById('month').value;
                XLSX.writeFile(wb, `${year}年${month}月考勤记录.xlsx`);
            }
        });
    </script>
</body>
</html>